package cn.uyunsky.platform.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import cn.uyunsky.platform.BeanFactoryUtil;
import cn.uyunsky.platform.config.factorybean.ConfigBean;
import cn.uyunsky.platform.config.factorybean.ConfigFactoryBean;
import cn.uyunsky.platform.config.reader.ComboxReader;
import cn.uyunsky.platform.config.reader.SqlTemplateReader;
import cn.uyunsky.platform.jaxb.XmlConvert;

public class ConfigFactoryImpl implements ConfigFactory {

	private static Log log = LogFactory.getLog(ConfigFactoryImpl.class);

	// Factory持有所有Reader;在内存中保存了所有的配置信息
	private static Map<String, ConfigReader<ConfigBeanInterface>> configReaders = new HashMap<String, ConfigReader<ConfigBeanInterface>>();;

	private PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();

	//通过命名注入
	private XmlConvert xmlConvert;

	public void setXmlConvert(XmlConvert xmlConvert) {
		this.xmlConvert = xmlConvert;
	}

	private Resource[] configLocation;

	public void setConfigLocation(Resource[] configLocation) {
		this.configLocation = configLocation;
	}

	@Override
	public void loadAll() {
		configReaders.clear();
		if (this.configLocation != null) {
			for (Resource location : this.configLocation) {
                log.info("加载配置文件工厂:"+location);
				InputStream is = null;
				try {
					is = location.getInputStream();
					ConfigFactoryBean factory = xmlConvert.unpack(ConfigFactoryBean.class, is);
					List<ConfigBean> list = factory.getConfig();
					for (ConfigBean config : list) {

						ConfigLoader loader = config.getLoaderInstance();
						if (!configReaders.containsKey(config.getReader())) {
							configReaders.put(config.getReader(), config.getReaderInstance());
						}
						ConfigReader<ConfigBeanInterface> reader = configReaders.get(config.getReader());

						//读取path下所有文件,分别加载
						String path = config.getPath();
						Resource[] resources = patternResolver.getResources(path);
						for (Resource resource : resources) {
							ConfigBeanInterface obj = loader.loadConfig(resource, config.getBeanClass());
							reader.addBean(obj);
						}
					}
				} catch (Exception ex) {
					log.warn("Could not load config from " + location + ": " + ex.getMessage());
					throw new RuntimeException("Could not load configfile from " + location, ex);
				} finally {
					if (is != null) {
						try {
							is.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
            log.fatal("==========加载配置文件完成,平台启动成功!==========");
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T getReader(Class<T> readerClass) {
		String reader = readerClass.getName();
		return (T) configReaders.get(reader);
	}

	public static void main(String[] args) {
		ConfigFactory configFactory = (ConfigFactory) BeanFactoryUtil.getBean("configFactory");

		SqlTemplateReader sqlreader = configFactory.getReader(SqlTemplateReader.class);
		System.out.println(sqlreader.getSql("test"));
		
		
		ComboxReader comreader = configFactory.getReader(ComboxReader.class);
		System.out.println(comreader.getEntrys("schedule_state"));
	}
}
